<?php
declare(strict_types=1);

namespace app\middleware\api\admin;

class ApiTokenCheck
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return \think\Response
     */
    public function handle($request, \Closure $next)
    {
        $admin_auth = \app\library\api\admin\Auth::instance();
        $re_jwt = $admin_auth->decodeJWT($admin_auth->getAuthHeader($request));
        if ($re_jwt['code'] != 200) {
            return api_response(-1, 'token无效' . $re_jwt['msg']);
        } else {
            $request->x_token_user = $re_jwt['data']['data'];
            if (isset($request->x_token_user['from']) && $request->x_token_user['from'] != '1') {
                return api_response(-1, 'token无效 来源错误');
            }

            // 获取数据权限
            $request->x_user_data_scope = $admin_auth->getDataScope($request->x_token_user['id']);
        }

        return $next($request);
    }
}
